package com.ndp.fb.walle.helper;

import com.ndp.fb.config.ConfigCentre;
import com.ndp.fb.constant.ConfigConst;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by Administrator on 2015/3/27.
 */
public class FbCommonsMultipartResolver extends CommonsMultipartResolver {

    String imgUrl = "adimages";
    String videoUrl = "advideo";

    /**
     * Parse the given servlet request, resolving its multipart elements.
     *
     * @param request the request to parse
     * @return the parsing result
     * @throws MultipartException if multipart resolution failed.
     */
    protected MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException {
        String encoding = determineEncoding(request);
        FileUpload fileUpload = prepareFileUpload(encoding);
        //TODO 不同的请求使用不同的大小
        String requestURI = request.getRequestURI();
        fileUpload.setProgressListener(new ProgressListener() {
            @Override
            public void update(long pBytesRead, long pContentLength, int pItems) {
                System.out.println("xxxxxxxxxxxxxxx>>>pBytesRead"+pBytesRead);
                System.out.println("xxxxxxxxxxxxxxx>>>pContentLength"+pContentLength);
                System.out.println("xxxxxxxxxxxxxxx>>>pItems"+pItems);
            }
        });
        Long maxSize = -1L;
        if (requestURI.contains(videoUrl)) {
            maxSize = ConfigCentre.getLong(ConfigConst.UPLOAD_VIDEO_MAX_SIZE);
        } else if (requestURI.contains(imgUrl)) {
            maxSize = ConfigCentre.getLong(ConfigConst.UPLOAD_IMG_MAX_SIZE);
        }
        logger.info("请求路径>>>" + requestURI + ",最大允许上传大小MaxSize" + maxSize);
        fileUpload.setFileSizeMax(maxSize);
        try {
            List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
            return parseFileItems(fileItems, encoding);
        } catch (FileUploadBase.SizeLimitExceededException ex) {
            throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);
        } catch (FileUploadException ex) {
            throw new MultipartException("Could not parse multipart servlet request", ex);
        }
    }
}
